package cn.exrick.xboot.base.serviceimpl

import cn.exrick.xboot.base.dto.*
import cn.exrick.xboot.base.entity.EnterpriseEmployee
import cn.exrick.xboot.base.entity.Job
import cn.exrick.xboot.base.entity.SecurityAdvisorServiceEnterprise
import cn.exrick.xboot.base.entity.SupervisionUser
import cn.exrick.xboot.base.mapper.EnterpriseEmployeeMapper
import cn.exrick.xboot.base.service.*
import cn.exrick.xboot.base.vo.*
import cn.exrick.xboot.core.common.constant.CommonConstant
import cn.exrick.xboot.core.common.utils.PageUtil
import cn.exrick.xboot.core.common.utils.ResultUtil
import cn.exrick.xboot.core.common.utils.SecurityUtil
import cn.exrick.xboot.core.common.utils.ToolUtil
import cn.exrick.xboot.core.common.vo.PageVo
import cn.exrick.xboot.core.common.vo.Result
import cn.exrick.xboot.core.entity.User
import cn.exrick.xboot.core.entity.UserRole
import cn.exrick.xboot.core.service.DepartmentService
import cn.exrick.xboot.core.service.RoleService
import cn.exrick.xboot.core.service.UserService
import cn.exrick.xboot.core.service.mybatis.IUserRoleService
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.google.common.collect.Maps
import lombok.SneakyThrows
import lombok.extern.slf4j.Slf4j
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

/**
 * 企业员工接口实现
 * @author Fei
 */
@Slf4j
@Service
@Transactional
open class IEnterpriseEmployeeServiceImpl : ServiceImpl<EnterpriseEmployeeMapper?, EnterpriseEmployee?>(), IEnterpriseEmployeeService {


    @Autowired
    private var iEnterpriseTrainingNeedsService: IEnterpriseTrainingNeedsService ?= null

    @Autowired
    private var securityUtil:SecurityUtil? = null

    @Autowired
    private var userService:UserService? = null

    @Autowired
    private var userRoleService: IUserRoleService? = null

    @Autowired
    private var departmentService: DepartmentService? = null

    @Autowired
    private var iJobService:IJobService? = null

    @Autowired
    private var iAreaService:IAreaService? = null

    @Autowired
    private var iUserRoleService:IUserRoleService? = null

    @Autowired
    private lateinit var iSecurityAdvisorServiceEnterpriseService: ISecurityAdvisorServiceEnterpriseService

    @Autowired
    private lateinit var iSupervisionUserService: ISupervisionUserService

    @Autowired
    private lateinit var iSecurityAdvisorService: ISecurityAdvisorService

    @Autowired
    private lateinit var iEnterpriseUserService: IEnterpriseUserService

    @Autowired
    private lateinit var redisTemplate: StringRedisTemplate

    @Autowired
    private lateinit var roleService: RoleService


    fun getEmployeeNumByDepartmentId(departmentId: String?): Int {

        val num = userService!!.findByDepartmentId(departmentId).size
        return num.plus(departmentService!!.get(departmentId)?.run {

            if (CommonConstant.PARENT_ID == parentId) 0 else getEmployeeNumByDepartmentId(parentId)
        } ?: 0)
    }

    override fun createEnterpriseEmployee(enterpriseEmployeeDto: EnterpriseEmployeeDto?): Result<Any?>? {


        return enterpriseEmployeeDto?.let {

            userService!!.findByMobile(it.mobile)?.run {  return ResultUtil.error(202, "手机号重复") }
             User().apply {

                 //1.添加用户
                 ToolUtil.copyProperties(it, this)
                 username = it.mobile
                 password = BCryptPasswordEncoder().encode(it.password)
                 createBy = securityUtil!!.currUser.id
                 val userInsert = userService!!.save(this)

                 //2. 添加角色
                 it.roleIds?.let { it.forEach {

                     UserRole().apply {

                         userId = userInsert.id
                         roleId = it
                         userRoleService!!.save(this)
                     }
                 }}
                 //3. 添加员工扩展类
                 EnterpriseEmployee().apply {

                     jobId = it.jobId
                     userId = userInsert.id
                     areaId = it.areaId
                     enterpriseId = iEnterpriseUserService.getEnterpriseIdByEmployeeUserId(securityUtil!!.currUser.id)

                     //4. 序号
                     sort = when (enterpriseEmployeeDto.position) {
                         0 -> getEmployeeNumByDepartmentId(enterpriseEmployeeDto.departmentId) + 1
                         1 -> {
                             list(KtQueryWrapper(EnterpriseEmployee::class.java).ge(EnterpriseEmployee::sort, getById(enterpriseEmployeeDto
                                 .employeeId)?.sort)).filter { userService!!.get(it!!.userId)?.departmentId == enterpriseEmployeeDto.departmentId }
                                 .forEach {
                                     it!!.sort = it.sort!!.plus(1)
                                     updateById(it)
                                 }
                             getById(enterpriseEmployeeDto.employeeId)?.sort
                         }
                         else -> {
                             list(KtQueryWrapper(EnterpriseEmployee::class.java).lt(EnterpriseEmployee::sort, getById(enterpriseEmployeeDto
                                 .employeeId)?.sort)).filter { userService!!.get(it!!.userId)?.departmentId == enterpriseEmployeeDto.departmentId }
                                 .forEach {
                                     it!!.sort = it.sort!! - 1
                                     updateById(it)
                                 }
                             getById(enterpriseEmployeeDto.employeeId)?.sort!! - 1
                         }
                     }
                     save(this)
                 }
             }

            return ResultUtil.success("添加员工成功")
        } ?: ResultUtil.error("参数缺失")
    }

    override fun updateEnterpriseEmployee(enterpriseEmployeeDto: EnterpriseEmployeeDto?): Result<Any?>? {

        return enterpriseEmployeeDto?.let {

            getById(it.id)?.run {

                //1.修改用户
                userService!!.update(userService!!.get(userId)?.apply {

                    ToolUtil.copyProperties(it, this)
                    id = userId
                })

                //2.修改角色
                iUserRoleService!!.removeUserRolesByUserId(userId)
                iUserRoleService!!.addUserRole(userId, it.roleIds)

                //3.修改员工
                ToolUtil.copyProperties(it, this)
                enterpriseId = iEnterpriseUserService.getEnterpriseIdByEmployeeUserId(securityUtil!!.currUser.id)
                updateById(this)

                ResultUtil.success<Any?>("修改成功！")
            } ?: ResultUtil.error(201, "当前员工不存在")
        } ?: ResultUtil.error(202, "参数缺失")
    }

    @SneakyThrows
    override fun removeEnterpriseEmployee(ids: Array<out String>?): Result<Any?>? {

         ids?.forEach {

            getById(it)?.run {

                //1. 移除用户
                userService!!.delete(userId)

                //2. 移除角色
                iUserRoleService!!.removeUserRolesByUserId(userId)

                //3. 移除员工
                removeById(it)
            }
        }

        return ResultUtil.success("移除成功")
    }

    override fun forbiddenEnterpriseEmployee(ids: Array<out String>?): Result<Any?>? {

        ids?.forEach {

            getById(it)?.run {

                userService!!.update(userService!!.get(userId)?.apply {

                    status = when (status) {
                        CommonConstant.STATUS_NORMAL -> {
                            CommonConstant.STATUS_DISABLE
                        }
                        else -> {
                            CommonConstant.STATUS_NORMAL
                        }
                    }
                })
            }
        }
        return ResultUtil.success("操作成功！")

    }

    override fun settingAffectedPerson(enterpriseSafePersonDto: EnterpriseSafePersonDto?): Result<Any?>? {

        return enterpriseSafePersonDto?.let {

            getById(it.enterpriseEmployeeId)?.apply {

                it.enterpriseAffectedEmployeeIds?.let { ids ->

                    this.affectedMePerson = if (ToolUtil.isNotEmpty(this.affectedMePerson)) this.affectedMePerson.plus(",").plus(ids) else ids
                    updateById(this)

                    ids.split(",").forEach { idsAdd ->

                        getById(idsAdd)?.apply {

                            this.meAffectedPerson = if (ToolUtil.isNotEmpty(this.meAffectedPerson)) this.meAffectedPerson.plus(",").plus(it.enterpriseEmployeeId) else it.enterpriseEmployeeId
                            updateById(this)
                        }
                    }
                }
            }

            return ResultUtil.success("设置影响我的安全提醒人成功")
        } ?: ResultUtil.error("参数缺失")
    }

    override fun getAffectedPersonList(id: String?): Result<MutableList<EnterpriseEmployeeVo>>? {

        val employeeId: String? = id?.run { id } ?: getOne(KtQueryWrapper(EnterpriseEmployee::class.java).eq(EnterpriseEmployee::userId, securityUtil!!.currUser.id))?.id
       return getById(employeeId)?.run {

           if (affectedMePerson == "" && affectedMePerson == " ") {
               return ResultUtil.error(202, "暂无数据")
           }
           affectedMePerson?.let { ids ->

               return if (ToolUtil.isNotEmpty(ToolUtil.setListToNul(ToolUtil.splitterStr(ids)))) {

                   ResultUtil.data(ToolUtil.splitterStr(ids).filter { it != "" && it != " " && it != null }.map { getEnterpriseEmployeeVoById(it)!! }.toMutableList(), "")
               }else{

                   ResultUtil.error(202, "暂无数据")
               }

           } ?: ResultUtil.error<MutableList<EnterpriseEmployeeVo>>(201, "暂无数据")
        } ?: ResultUtil.error(202, "参数异常")
    }

    override fun getEmployeeInfo(employeeUserId: String?): Result<EmployeeInfoVo?>? {


        val userId = if (ToolUtil.isNotEmpty(employeeUserId)) employeeUserId else securityUtil!!.currUser.id
        return getOne(KtQueryWrapper(EnterpriseEmployee::class.java).eq(EnterpriseEmployee::userId, userId))?.run {

            ResultUtil.data(EmployeeInfoVo().apply {

                ToolUtil.copyProperties(securityUtil!!.currUser, this)

                ToolUtil.copyProperties(this@run, this)

                jobName = jobId?.let { iJobService!!.getJobName(it) }
                departmentName = securityUtil!!.currUser.departmentId?.let { departmentService!!.getDepartmentTitle(it) }
                enterpriseName = iEnterpriseUserService.getById(enterpriseId)?.companyName
                areaName = securityUtil!!.currUser.areaId?.let { iAreaService!!.getAreaFullNameByAreaId(it) }
                roleName = userRoleService!!.findByUserId(securityUtil!!.currUser.id).map { it.name }.joinToString(",")
            })
        }
    }

    override fun getUserByType(type: Int): Result<List<UserCommonVo>>? {

       return when (type) {

            //安全顾问
            1 -> {

                return ToolUtil.setListToNul(iSecurityAdvisorServiceEnterpriseService.list(KtQueryWrapper(SecurityAdvisorServiceEnterprise::class.java)
                        .eq(SecurityAdvisorServiceEnterprise::enterpriseUserId, iEnterpriseUserService.getEnterpriseIdByEmployeeUserId(securityUtil!!.currUser.id))
                        .eq(SecurityAdvisorServiceEnterprise::serviceStatus, true)
                        .orderByDesc(SecurityAdvisorServiceEnterprise::createTime)))?.run {

                    ResultUtil.data(mapNotNull {
                        UserCommonVo().apply {

                            userService!!.get(it?.createBy)?.let { ToolUtil.copyProperties(it, this) }
                        }
                    })
                }
            }


            //同级别的上报信息接收员
            2 -> {

                return iSupervisionUserService.list(KtQueryWrapper(SupervisionUser::class.java)
                        .eq(SupervisionUser::areaId, securityUtil!!.currUser.areaId)
                        .orderByDesc(SupervisionUser::createTime))?.run {


                    val supervisionList = filter { iUserRoleService!!.findByUserId(it?.userId).map { it.id }.contains(when (iAreaService!!.getById(securityUtil!!.currUser.areaId)?.areaLevel) {

                        2 -> {
                            CommonConstant.ROLE_COUNTY_REPORT
                        }
                        else -> {
                            CommonConstant.ROLE_TOWN_REPORT
                        }
                    }) }

                    if (ToolUtil.isNotEmpty(ToolUtil.setListToNul(supervisionList))) {

                        return ResultUtil.data(supervisionList.mapNotNull { UserCommonVo().apply { ToolUtil.copyProperties(userService!!.get(it?.userId), this) } }, "获取数据成功！")
                    } else {

                        ResultUtil.error(201, "暂无数据！")
                    }

                }
            }

            //获取本企业安全生产管理人员
            3 -> {

                return list(KtQueryWrapper(EnterpriseEmployee::class.java)
                        .eq(EnterpriseEmployee::enterpriseId, getEnterpriseEmployeeVoById(securityUtil!!.currUser.id))
                        .orderByDesc(SupervisionUser::createTime))?.run {


                    val safeEmployeeList = filter { iUserRoleService!!.findByUserId(it?.userId).map { it.id }.contains(roleService.getRoleIdByRoleName(CommonConstant.ROLE_SECURITY_MANAGER)) }

                    if (ToolUtil.isNotEmpty(ToolUtil.setListToNul(safeEmployeeList))) {

                        return ResultUtil.data(safeEmployeeList.mapNotNull { UserCommonVo().apply { ToolUtil.copyProperties(userService!!.get(it?.userId), this) } }, "获取数据成功！")
                    } else {

                        ResultUtil.error(201, "暂无数据！")
                    }

                }
            }

           //获取本企业高管人员
            4 -> {

                return list(KtQueryWrapper(EnterpriseEmployee::class.java)
                        .eq(EnterpriseEmployee::enterpriseId, getEnterpriseEmployeeVoById(securityUtil!!.currUser.id))
                        .orderByDesc(SupervisionUser::createTime))?.run {


                    val topEmployeeList = filter { iUserRoleService!!.findByUserId(it?.userId).map { it.id }.contains(roleService.getRoleIdByRoleName(CommonConstant.ROLE_TOP_MANAGER)) }

                    if (ToolUtil.isNotEmpty(ToolUtil.setListToNul(topEmployeeList))) {

                        return ResultUtil.data(topEmployeeList.mapNotNull { UserCommonVo().apply { ToolUtil.copyProperties(userService!!.get(it?.userId), this) } }, "获取数据成功！")
                    } else {

                        ResultUtil.error(201, "暂无数据！")
                    }

                }

            }
           else -> ResultUtil.error(201, "暂无数据")
       }


    }

    override fun getEmployeeIdByUserId(userId: String?): String? {

        return getOne(KtQueryWrapper(EnterpriseEmployee::class.java).eq(EnterpriseEmployee::userId, userId))?.id
    }

    override fun getAffectedPersonList(): Result<MutableList<UserCommonVo>> {
        TODO("Not yet implemented")
    }

    override fun getMeAffectedPersonList(id: String?): Result<MutableList<EnterpriseEmployeeVo>>? {

        val employeeId: String? = id?.run { id } ?: getOne(KtQueryWrapper(EnterpriseEmployee::class.java).eq(EnterpriseEmployee::userId, securityUtil!!.currUser.id))?.id
        return getById(employeeId)?.run {

            if (meAffectedPerson == "") {
                return ResultUtil.error(202, "暂无数据")
            }
            meAffectedPerson?.let { ids ->

                return if (ToolUtil.isNotEmpty(ToolUtil.setListToNul(ToolUtil.splitterStr(ids)))) {

                    ResultUtil.data(ToolUtil.splitterStr(ids).filter { it != "" && it != " " && it != null }.map { getEnterpriseEmployeeVoById(it)!! }.toMutableList(), "")
                }else{

                    ResultUtil.error(202, "暂无数据")
                }
            } ?: ResultUtil.error<MutableList<EnterpriseEmployeeVo>>(201, "暂无数据")
        } ?: ResultUtil.error(202, "参数异常")
    }

    override fun removeAffectedPersonList(ids: Array<out String>, id: String?): Result<Any?>? {

        return getById(id!!)?.let {

            it.affectedMePerson?.apply {

                val affectedMePersonList = this.split(",").toMutableList()
                ids.forEach { id ->

                    affectedMePersonList.remove(id)

                    //我的徒弟也要移除
                    getById(id)?.apply {

                       this.meAffectedPerson = this.meAffectedPerson?.split(",")?.toMutableList()?.let { meAffectedPersonIdList ->

                           meAffectedPersonIdList.remove(id)
                           ToolUtil.joinerList(meAffectedPersonIdList)
                        }
                        updateById(this)
                    }
                }

                it.affectedMePerson = ToolUtil.joinerList(affectedMePersonList)
                updateById(it)
            }
            return ResultUtil.success("移除成功")
        } ?: ResultUtil.error(201, "不存在此数据！")
    }

    override fun settingSafeMasterPerson(enterpriseSafePersonDto: EnterpriseSafePersonDto?): Result<Any?>? {

       return enterpriseSafePersonDto?.let {

            getById(it.enterpriseEmployeeId)?.apply {

                it.enterpriseAffectedEmployeeIds?.let { ids ->

                    mySafeMasterPerson = if (ToolUtil.isNotEmpty(this.mySafeMasterPerson)) this.mySafeMasterPerson.plus(",").plus(ids) else ids
                    updateById(this)

                    ids.split(",").forEach { idsAdd ->

                        getById(idsAdd)?.apply {

                            this.mySafePrentice = if (ToolUtil.isNotEmpty(this.mySafePrentice)) this.mySafePrentice.plus(",").plus(it.enterpriseEmployeeId) else it.enterpriseEmployeeId
                            updateById(this)
                        }
                    }
                }

            }

           return ResultUtil.success("设置安全师傅成功！")
        } ?: ResultUtil.error("参数缺失")
    }

    override fun getSafeMasterPerson(id: String?): Result<MutableList<EnterpriseEmployeeVo>>? {


        val employeeId = id?.let { id } ?: getOne(KtQueryWrapper(EnterpriseEmployee::class.java).eq(EnterpriseEmployee::userId, securityUtil!!.currUser.id))?.id
        return getById(employeeId)?.let {

            if (it.mySafeMasterPerson == "") {
                return ResultUtil.error(202, "暂无数据")
            }

            it.mySafeMasterPerson?.let { ids ->

                return if (ToolUtil.isNotEmpty(ToolUtil.setListToNul(ToolUtil.splitterStr(ids)))) {

                    ResultUtil.data(ToolUtil.splitterStr(ids).filter { it != "" && it != " " && it != null }.map { getEnterpriseEmployeeVoById(it)!! }.toMutableList(), "")
                }else{

                    ResultUtil.error(202, "暂无数据")
                }
            } ?: ResultUtil.error<MutableList<EnterpriseEmployeeVo>>(201, "暂无数据")
        } ?: ResultUtil.error(202, "参数异常")
    }

    override fun removeSafeMasterPerson(ids: Array<out String>, id: String?): Result<Any?>? {

        return getById(id!!)?.let {

            it.mySafeMasterPerson?.apply {

                val mySafeMasterPersonList = this.split(",").toMutableList()
                ids.forEach { id ->

                    mySafeMasterPersonList.remove(id)


                    //我的徒弟也要移除
                    getById(id)?.apply {

                        this.mySafePrentice = this.mySafePrentice?.split(",")?.toMutableList()?.let { mySafePrenticeIdList ->

                            mySafePrenticeIdList.remove(id)
                            ToolUtil.joinerList(mySafePrenticeIdList)
                        }
                        updateById(this)
                    }

                }

                it.mySafeMasterPerson = ToolUtil.joinerList(mySafeMasterPersonList)
                updateById(it)
            }
            return ResultUtil.success("移除成功")
        } ?: ResultUtil.error(201, "不存在此数据！")

    }

    override fun getEnterpriseEmployeeList(enterpriseEmployeeSearchDto: EnterpriseEmployeeSearchDto?, pageVo: PageVo): Result<MutableMap<String, Any?>?>? {

         return ToolUtil.setListToNul(list(KtQueryWrapper(EnterpriseEmployee::class.java)
                 .eq(EnterpriseEmployee::enterpriseId, iEnterpriseUserService.getEnterpriseIdByEmployeeUserId(securityUtil!!.currUser.id))
                 .orderByDesc(EnterpriseEmployee::sort)))?.let {

            var enterpriseEmployeeVos = it.map { enterpriseEmployee -> getEnterpriseEmployeeVoById(enterpriseEmployee!!.id) }.toMutableList()

            //筛选条件
            enterpriseEmployeeSearchDto?.apply {


                if (mobile != null && mobile != "") {

                    enterpriseEmployeeVos = enterpriseEmployeeVos.filter { enterpriseEmployeeVo -> enterpriseEmployeeVo!!.mobile!!.contains(this.mobile!!) }.toMutableList()
                }

                if (sex != null && sex != "") {

                    enterpriseEmployeeVos = enterpriseEmployeeVos.filter { enterpriseEmployeeVo -> enterpriseEmployeeVo!!.sex!! == this.sex }.toMutableList()
                }

                if (departmentId != null && departmentId != "") {

                    enterpriseEmployeeVos = enterpriseEmployeeVos.filter { enterpriseEmployeeVo ->enterpriseEmployeeVo != null && enterpriseEmployeeVo.departmentId != null && enterpriseEmployeeVo.departmentId != "" && enterpriseEmployeeVo.departmentId == this.departmentId }.toMutableList()
                }

                if (jobId != null && jobId != "") {

                    enterpriseEmployeeVos = enterpriseEmployeeVos.filter { enterpriseEmployeeVo -> enterpriseEmployeeVo!!.jobId!! == (this.jobId!!) }.toMutableList()
                }
            }

             val  result: MutableMap<String, Any?> = Maps.newHashMap()
             result["size"] = enterpriseEmployeeVos.size
             result["content"] = PageUtil.listToPage(pageVo, enterpriseEmployeeVos)

             ResultUtil.data(result, "获取员工列表成功")
         } ?: ResultUtil.error(201, "暂无数据！")
    }



    /**
     * 获取员工实体封装类
     */
    private fun getEnterpriseEmployeeVoById(id: String): EnterpriseEmployeeVo? {

        return getById(id)?.let {

             EnterpriseEmployeeVo().apply {

                 userService!!.get(it.userId)?.let { user ->

                     ToolUtil.copyProperties(user, this)
                     sort = "P".plus(it.sort)
                     departmentTitle = user.departmentId?.run { departmentService!!.getDepartmentTitle(user.departmentId) }
                     areaName = iAreaService!!.getAreaFullNameByAreaId(areaId)
                     jobName = iJobService!!.getJobName(it.jobId!!)
                     enterpriseName = iEnterpriseUserService.getEnterpriseNameById(it.enterpriseId)
                     joinJobTime = it.createTime
                     userRoleService!!.findByUserId(it.userId)?.let { roles ->

                         this.roles = roles

                         ToolUtil.copyProperties(it, this)
                     }
                 }
             }
        }
    }


    override fun settingEmployeeDimission(ids: Array<out String>?): Result<Any?>? {

        ids?.forEach {

            getById(it)?.run {

                dimission = !dimission!!
                updateById(this)
            }
        }

        return ResultUtil.success("操作成功")
    }

    override fun publishOrUpdateEnterpriseTrainingNeed(enterpriseTrainingNeedDto: EnterpriseTrainingNeedDto): Result<Any?>? {

        return iEnterpriseTrainingNeedsService!!.publishOrUpdateEnterpriseTrainingNeed(enterpriseTrainingNeedDto)
    }

    override fun getMyPublishEnterpriseTrainingNeedList(pageVo: PageVo): Result<MutableMap<String, Any?>?> {

        return iEnterpriseTrainingNeedsService!!.getMyPublishEnterpriseTrainingNeedList(pageVo)
    }

    override fun removePublishEnterpriseTrainingNeed(ids: Array<out String>): Result<Any?>? {

        return iEnterpriseTrainingNeedsService!!.removePublishEnterpriseTrainingNeed(ids)
    }

    override fun createOrUpdateJob(job: Job?): Result<Any?>? {

        return iJobService!!.createOrUpdateJob(job)
    }

    override fun removeJob(ids: Array<out String>): Result<Any?>? {

        return iJobService!!.removeJob(ids)
    }

    override fun getJobList(pageVo: PageVo): Result<MutableMap<String, Any?>>? {

        return iJobService!!.getJobList(pageVo)
    }

    override fun getEmployeeTrainingInfo(employeeId: String): EnterpriseEmployeeTrainingVo? {

        return getById(employeeId)?.run {

            EnterpriseEmployeeTrainingVo().apply {

                //用户信息
                userService!!.get(userId)?.let {

                    ToolUtil.copyProperties(it, this)
                    userId = it.id
                }

                //企业信息
                enterpriseName = iEnterpriseUserService.getById(enterpriseId)?.companyName

                //岗位信息
                jobName = iJobService!!.getJobName(jobId!!)
            }
        }
    }

    override fun getUserIdByEmployeeId(employeeId: String): String? {

        return getById(employeeId)?.run { userId }
    }

    override fun getDepartmentTree(parentId: String?, enterpriseId: String): Result<MutableList<DepartmentVo>>? {

        return ToolUtil.setListToNul(departmentService!!.findByParentIdAndEnterpriseIdOrderByCreateTime(
                if (ToolUtil.isNotEmpty(parentId)) parentId else CommonConstant.PARENT_ID,
                enterpriseId))?.run {

            ResultUtil.data(mapNotNull {

                DepartmentVo().apply {

                    ToolUtil.copyProperties(it, this)
                    //计算当前部门的人数
                    employeeNum = userService!!.findByDepartmentId(it.id).count()

                    departmentNext = ToolUtil.setListToNul(departmentService!!.findByParentIdOrderBySortOrder(it.id!!, false))?.run {

                        mapNotNull {
                            DepartmentVo().apply {

                                ToolUtil.copyProperties(it, this)
                                //计算当前部门的人数
                                employeeNum = userService!!.findByDepartmentId(it.id).count()

                                departmentNext = getDepartmentVo(it.id)
                            }
                        }.toMutableList()
                    }
                }
            }.toMutableList(), "获取部门信息成功！")
        } ?: ResultUtil.error(201, "暂无数据")
    }

    private fun getDepartmentVo(id: String): MutableList<DepartmentVo> {

       return ToolUtil.setListToNul(departmentService!!.findByParentIdOrderBySortOrder(id, false))?.run {

            mapNotNull {

                DepartmentVo().apply {

                    ToolUtil.copyProperties(it, this)
                    //计算当前部门的人数
                    employeeNum = userService!!.findByDepartmentId(it.id).count()

                    departmentNext = getDepartmentVo(it.id)
                }
            }.toMutableList()
        }?: mutableListOf()
    }


    override fun getEnterpriseEmployeeList(enterpriseId: String): Result<MutableList<UserCommonVo>> {

        return ToolUtil.setListToNul(list(KtQueryWrapper(EnterpriseEmployee::class.java)
                .eq(EnterpriseEmployee::enterpriseId, enterpriseId)
                .orderByDesc(EnterpriseEmployee::createTime)))?.run {

            ResultUtil.data(mapNotNull {
                UserCommonVo().apply {
                    userService!!.get(it?.userId)?.let { user ->

                        ToolUtil.copyProperties(user, this)
                        id = it?.id
                    }
                }
            }.toMutableList(), "获取企业员工成功")
        } ?: ResultUtil.error(201, "暂无数据！")
    }

    override fun getEmployeeListByDepartment(departmentId: String?): Result<MutableList<UserCommonVo>>? {

       return ToolUtil.setListToNul(userService!!.findByDepartmentId(departmentId))?.run {

            ResultUtil.data(mapNotNull { UserCommonVo().apply { ToolUtil.copyProperties(this@run, this) } }.toMutableList(), "获取员工数据成功")
        } ?: ResultUtil.error(201, "暂无数据！")
    }

    override fun updateEmployeeInfo(employeeInfoDto: EmployeeInfoDto): Result<Any?>? {

        employeeInfoDto.nickname?.run {

            userService!!.update(securityUtil!!.currUser.apply { ToolUtil.copyProperties(employeeInfoDto, this) })

            redisTemplate.delete("user::" + securityUtil!!.currUser.username)
        }


        getById(getEmployeeIdByUserId(securityUtil!!.currUser.id))?.run {

            employeeInfoDto.selfPic?.let { selfPic = it }
            employeeInfoDto.lifePic?.let { lifePic = it }
            employeeInfoDto.familyPic?.let { familyPic = it }

            updateById(this)
        }

        return ResultUtil.success("成功")
    }


    override fun getJobIdByEmployeeId(employeeId: String): String? {

        return getOne(KtQueryWrapper(EnterpriseEmployee::class.java).eq(EnterpriseEmployee::userId, employeeId))?.jobId
    }

    override fun getEnterpriseEmployeeTotalCount(enterpriseId: String): Int {

        return count(KtQueryWrapper(EnterpriseEmployee::class.java).eq(EnterpriseEmployee::enterpriseId, enterpriseId))
    }

}
